package com.example.foodsy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.foodsy.entity.CompanyInfo;
import com.example.foodsy.mapper.CompanyInfoMapper;
import com.example.foodsy.service.StatsService;
import com.example.foodsy.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StatsServiceImpl implements StatsService {

    @Autowired
    private CompanyInfoMapper companyInfoMapper;

    /**
     * 逻辑1：近12个月企业注册数量趋势
     * 步骤：①生成近12个月的月份列表 ②数据库分组查询每月注册数 ③补全无数据的月份为0
     * 返回结果示例
     * {
     *     "success": true,
     *     "errorMsg": null,
     *     "data": [
     *         {
     *             "month": "2024-11",
     *             "count": 0
     *         },
     */
    @Override
    public Result getMonthlyCompanyTrend() {
        //初始化时间和数据结构
        LocalDate now = LocalDate.now();
        List<String> months = new ArrayList<>();
        Map<String, Integer> monthCountMap = new HashMap<>();
        //生成过去 12 个月的月份字符串
        /*
        * 循环生成过去 12 个月的日期（从 11 个月前到当前月）
        * 将每个月格式化为 "yyyy-MM" 形式的字符串
         *初始化每个月的统计数量为 0，确保即使某个月没有数据也会被包含在结果中
         */
        for (int i = 11; i >= 0; i--) {
            LocalDate monthDate = now.minusMonths(i);
            String monthStr = monthDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            months.add(monthStr);
            monthCountMap.put(monthStr, 0);
        }

        // 用QueryWrapper处理含DATE_FORMAT的字符串查询
        QueryWrapper<CompanyInfo> queryWrapper = Wrappers.query();
        queryWrapper.select(
                        //将create_time格式化成年月形式，别名为month_str
                        "DATE_FORMAT(reg_date, '%Y-%m') as month_str",
                       //统计每个月的记录数，别名为count
                        "COUNT(id) as count"
                )
                .ge("reg_date", now.minusMonths(12)) // 用字符串字段名匹配数据库
                .groupBy("month_str")
                .orderByAsc("month_str");

        //执行查询并处理结果
        List<Map<String, Object>> dbResults = companyInfoMapper.selectMaps(queryWrapper);

        dbResults.forEach(dbResult -> {
            String monthStr = (String) dbResult.get("month_str");
            Integer count = ((Number) dbResult.get("count")).intValue();
            monthCountMap.put(monthStr, count);
        });

        List<Map<String, Object>> resultList = months.stream().map(month -> {
            Map<String, Object> item = new HashMap<>();
            item.put("month", month);
            item.put("count", monthCountMap.get(month));
            return item;
        }).collect(Collectors.toList());

        return Result.ok(resultList);
    }

    /**
     * 逻辑2：按省份统计企业注册数量
     * 步骤：数据库按“prov_id（省份ID）”分组，统计各省份的企业数
     * （可选：若需“省份名称”，需关联 province 表查询，此处简化为仅返回省份ID和数量）
     *   返回结果示例：
     *   "success": true,
     *     "errorMsg": null,
     *     "data": [
     *         {
     *             "prov_id": 32,
     *             "count": 4
     *         },
     */
    @Override
    public Result getCompanyCountByProvince() {
        // 替换为QueryWrapper，用字符串字段适配分组/排序
        QueryWrapper<CompanyInfo> queryWrapper = Wrappers.query();
        queryWrapper.select("prov_id", "COUNT(id) as count")
                .groupBy("prov_id")
                .orderByDesc("count");

        List<Map<String, Object>> provCountList = companyInfoMapper.selectMaps(queryWrapper);
        return Result.ok(provCountList);
    }


    /**
     * 逻辑3：按企业类型统计注册数量分布
     * 步骤：数据库按“type（企业类型：1养殖/2屠宰/3批发/4零售）”分组，统计各类型数量
     * 返回数据示例：
     * "success": true,
     *     "errorMsg": null,
     *     "data": [
     *         {
     *             "typeName": "养殖企业",
     *             "count": 4,
     *             "type": 1
     *         },
     */
    @Override
    public Result getCompanyCountByType() {
        // QueryWrapper，用字符串字段适配分组/排序
        QueryWrapper<CompanyInfo> queryWrapper = Wrappers.query();
        queryWrapper.select("type", "COUNT(id) as count")
                .groupBy("type")
                .orderByAsc("type");

        List<Map<String, Object>> typeCountList = companyInfoMapper.selectMaps(queryWrapper);

        Map<Integer, String> typeNameMap = new HashMap<>() {{
            put(1, "养殖企业");
            put(2, "屠宰企业");
            put(3, "批发商");
            put(4, "零售商");
        }};

        List<Map<String, Object>> resultList = typeCountList.stream().map(item -> {
            Map<String, Object> newItem = new HashMap<>();
            Integer type = (Integer) item.get("type");
            newItem.put("type", type);
            newItem.put("typeName", typeNameMap.getOrDefault(type, "未知类型"));
            newItem.put("count", item.get("count"));
            return newItem;
        }).collect(Collectors.toList());

        return Result.ok(resultList);
    }
}